package com.scnlf.scnlf.portal.core.common.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.redisson.config.SingleServerConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Configuration
public class RedissonConfig {

  @Bean
  public RedissonClient redissonClient(ObjectMapper objectMapper, RedisProperties redisProperties) {
    Config config = new Config();
    config.setCodec(new JsonJacksonCodec(objectMapper));

    if("Cluster".equalsIgnoreCase(redisProperties.getMode())){
      ClusterServersConfig clusterServersConfig = config.useClusterServers();
      if(StringUtils.hasLength(redisProperties.getUrl())){
        log.info("Cluster hosts:", redisProperties.getUrl());
        List<String> serverList = Arrays.asList(redisProperties.getUrl().split(";"));
        serverList.forEach(clusterServersConfig::addNodeAddress);
      }
    } else if("Sentinel".equalsIgnoreCase(redisProperties.getMode())){
      SentinelServersConfig sentinelServersConfig = config.useSentinelServers();
      if(StringUtils.hasLength(redisProperties.getUrl())){
        log.info("Sentinel hosts:", redisProperties.getUrl());
        List<String> serverList = Arrays.asList(redisProperties.getUrl().split(";"));
        serverList.forEach(sentinelServersConfig::addSentinelAddress);
        if(StringUtils.hasLength(redisProperties.getPwd())){
          sentinelServersConfig.setPassword(redisProperties.getPwd());
        }
        if(StringUtils.hasLength(redisProperties.getMasterName())){
          sentinelServersConfig.setMasterName(redisProperties.getMasterName());
        }
        if(StringUtils.hasLength(redisProperties.getDb())){
          sentinelServersConfig.setDatabase(Integer.parseInt(redisProperties.getDb()));
        }
      }
    } else {
      SingleServerConfig singleServerConfig = config.useSingleServer();
      log.info("redis host: {}", redisProperties.getUrl());
      singleServerConfig.setAddress(redisProperties.getUrl()).setConnectionPoolSize(32);
      if (StringUtils.hasLength(redisProperties.getPwd())) {
        singleServerConfig.setPassword(redisProperties.getPwd());
      }
    }

    return Redisson.create(config);
  }

}
